package docmodel;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import utils.File_Utils;

/**
 * HTML --> HTML senza red&bold Markers --> PDF --> XDP
 * 
 * - richiede MS WORD installato - usa la libreria JACOB
 * 
 * @author andrea
 * 
 */
public class XDP_Creator
{
	/** OBJ */
	//private MSWord_Converter word_conv;
	
	/** OBJ */
	//private Livecycle_Converter livecycle_conv;
	
	/** OBJ */
	private HTML_Transformer html_tr;
	
	/** */
	private String inputFile; // ES: "prova.html"

	/** */
	private String htmlOutputFile; // ES: "prova-cleaned.html"

	/** */
	private String pdfOutputFile; // ES: "prova.pdf"

	/** */
	private String xdpOutputFile; // ES: "prova-temp.xdp"		 //-temp.xdp

	/** */
	private String baseFolder; //= "C:\\downloads\\";	//DEFAULT
	
	/** */
	private String liveCycleFolder; 
	
	/** */
	private boolean liveCycleFolder_SET = false;
	
	/**
	 * 
	 * @param htmlInputFile
	 * @param baseFolderPath
	 * @param xdpOutputFile
	 *             
	 */
	public XDP_Creator(String htmlInputFile, String baseFolderPath, String xdpOutputFile) 
	{
		init(htmlInputFile, baseFolderPath);
		this.xdpOutputFile = xdpOutputFile;
	}
	
	/**
	 * 
	 * @param htmlInputFile
	 * @param baseFolderPath
	 */
	public XDP_Creator(String htmlInputFile, String baseFolderPath)
	{
		init(htmlInputFile, baseFolderPath);
		this.xdpOutputFile = File_Utils.stripExtension(this.inputFile) + "-temp" //-temp.xdp
		+ ".xdp";	
	}

	/**
	 * @param htmlInputFile
	 * @param baseFolderPath
	 */
	private void init(String htmlInputFile, String baseFolderPath)
	{
		this.baseFolder = baseFolderPath;
		this.inputFile = new File(htmlInputFile).getAbsolutePath();
		
		pdfOutputFile  = File_Utils.stripExtension(this.inputFile) + ".pdf";  
		htmlOutputFile = File_Utils.stripExtension(this.inputFile) + "-cleaned"
				+ ".html";  
	}

	/**
	 * 
	 * @return
	 */
	public String getXdpOutputFile() {
		return xdpOutputFile;
	}

	/**
	 * 
	 * @param xdpOutputFile
	 */
	public void setXdpOutputFile(String xdpOutputFile) {
		this.xdpOutputFile = xdpOutputFile;
	}	

	/**
	 * @return the liveCycleFolder
	 */
	public String getLiveCycleFolder() {
		return liveCycleFolder;
	}

	/**
	 * @param liveCycleFolder the liveCycleFolder to set
	 */
	public void setLiveCycleFolder(String liveCycleFolder) {
		this.liveCycleFolder = liveCycleFolder;
		liveCycleFolder_SET  = true;					//FLAG
	}
	/**
	 * 
	 */
	public void run() 
	{
		//-----------------------------------------------------------------		
		// 1 - elimina "bold" & "red" dal file HTML per i MARKERS
		//-----------------------------------------------------------------			
		html_tr = new HTML_Transformer(inputFile, htmlOutputFile);	
		
		//-----------------------------------------------------------------		
		// 2 - 
		//-----------------------------------------------------------------		
		convert_HTML_to_PDF(htmlOutputFile, pdfOutputFile);		

		//-----------------------------------------------------------------		
		// 3 - 
		//-----------------------------------------------------------------		
		convert_PDF_to_XDP(pdfOutputFile, xdpOutputFile);															 	
	}

	/**
	 * @param htmlInputFile
	 *            TODO
	 * @param pdfOutputFile
	 *            TODO
	 * 
	 */
	private void convert_HTML_to_PDF(String htmlInputFile, String pdfOutputFile) 
	{
		boolean isVisible = true;
		boolean isSaveOnExit = true;

		ActiveXComponent oWord = new ActiveXComponent("Word.Application");
		oWord.setProperty("Visible", new Variant(isVisible));

		Dispatch oDocuments = oWord.getProperty("Documents").toDispatch();
		Dispatch oDocument = Dispatch.call(oDocuments, "Open", htmlInputFile)
				.toDispatch();
		// INPUT File(Path compreso) ---> "html_outputFile"

		Dispatch oSelection = oWord.getProperty("Selection").toDispatch();
		Dispatch oFind = oWord.call(oSelection, "Find").toDispatch();

		Object oWordBasic = Dispatch.call(oWord, "WordBasic").getDispatch();
		Dispatch.call((Dispatch) oWordBasic, "FileSaveAs", pdfOutputFile,
				new Variant(17));
		// OUTPUT File(Path compreso) ---> "pdf_outputFile" // 17 <=> PDF

		Dispatch.call(oDocument, "Close", new Variant(isSaveOnExit));
		oWord.invoke("Quit", new Variant[0]);
	}	
	
	/**
	 * @param pdfInputFile
	 *            File PDF da convertire
	 * @param xdpOutputFile
	 *            file XDP convertito da pdf
	 * 
	 */
	private void convert_PDF_to_XDP(String pdfInputFile, String xdpOutputFile) 
	{
		String cmd_string;
		Runtime rt;
		Process proc;
		
		cmd_string = baseFolder + "convertpdf.bat " + pdfInputFile + " "
				+ xdpOutputFile;

		//ALT
		if(liveCycleFolder_SET) 
			cmd_string = liveCycleFolder + 
						 "ConvertPDF.exe " + 
						 "in="   + pdfInputFile  +
						 "out="  + xdpOutputFile + 
						 " join=700 para=3000 lines=700";

		String[] cmd = new String[3];
		cmd[0] = "cmd.exe";
		cmd[1] = "/C";
		cmd[2] = cmd_string;

		rt = Runtime.getRuntime();

		try {
			proc = rt.exec(cmd_string);
			StreamGobbler errorGobbler = new StreamGobbler(
					proc.getErrorStream(), "ERROR");
			StreamGobbler outputGobbler = new StreamGobbler(
					proc.getInputStream(), "OUTPUT"); // any output?
			errorGobbler.start();
			outputGobbler.start();
			int exitVal = proc.waitFor(); // any error???
			System.out.println("ExitValue: " + exitVal);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
//		XDP_Creator converter = new XDP_Creator("prova.html",
//				"C:\\downloads\\", "c:\\prova.xdp");
//		converter.run();
	}


}

/**
 * 
 * @author giambattista
 * 
 */
 
class StreamGobbler extends Thread {
	InputStream is;
	String type;

	StreamGobbler(InputStream is, String type) {
		this.is = is;
		this.type = type;
	}

	public void run() {
		try {
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line = null;
			while ((line = br.readLine()) != null)
				System.out.println(type + ">" + line);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
}